package com.naiterui.ehp.bs.patient.service.impl;

import com.naiterui.ehp.bs.patient.bo.notice.subscribe.BaseSubscribe;
import com.naiterui.ehp.bs.patient.config.SubscribeConfig;
import com.naiterui.ehp.bs.patient.config.SubscribeProperties;
import com.naiterui.ehp.bs.patient.service.ISubscribeNoticeService;
import com.naiterui.ehp.bs.wechat.service.ISubscribeMsgApiService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * 订阅通知
 *
 * @author yangfuya
 * @version 1.0
 * @date 2021/4/9 16:12
 **/
@Slf4j
@Service
@RequiredArgsConstructor
public class ApSubscribeNoticeServiceImpl implements ISubscribeNoticeService {
    private final ISubscribeMsgApiService subscribeMsgApiService;
    private final SubscribeConfig subscribeConfig;

    @Override
    public Integer notice(BaseSubscribe param) {
        if (null == param || !param.validate()) {
            log.error("订阅通知发送失败，参数错误: {}", param);
            return 47003;
        }

        //通过label查询模板配置，来获取微信的templateId以及基础文案
        SubscribeProperties subscribeProperties = Optional.ofNullable(param.getTemplateLabel())
                .map(label -> subscribeConfig.templateMap().get(label)).get();
        if (null == subscribeProperties) {
            log.info("模板配置信息不全，请添加配置到subscribe-template.yml，配置: {}", subscribeProperties);
            return 47003;
        }

        //处理模板内容
        List<SubscribeProperties.Content> contentList = subscribeProperties.cloneContent();
        // 格式化处理文本内容
        param.handleContent(contentList);
        Map<String, Object> dataMap = contentList.stream()
                .collect(Collectors.toMap(SubscribeProperties.Content::getKey, SubscribeProperties.Content::getValue));
        return subscribeMsgApiService.sendSubscribe(param.getOpenId(), subscribeProperties.getTemplateId(), param.getTargetPage(), param.getMiniProgram(), dataMap);
    }
}
